package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.pojo.R;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.utils.RedisKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ZhaoJun on 2021/11/24 20:59
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @CacheEvict(value = "DISH_CACHE",key = "'DISH'+#dishDto.status+''+#dishDto.categoryId")
    public R addDish(@RequestBody DishDto dishDto){
        log.info("添加菜品:{}",dishDto.toString());

        dishService.saveWtihFlavor(dishDto);

        //删除该菜品分类列表的缓存数据
        redisTemplate.delete(RedisKeys.DISH + dishDto.getCategoryId() + "" + dishDto.getStatus());

        return R.success("添加菜品成功");
    }
    @GetMapping("page")
    public R page(Integer page,Integer pageSize,String name){
        log.info("菜品管理分页查询:{}",page,pageSize,name);

        if(null==name){
            name="";
        }
        //1 构造分页条件对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        // TODO: 2021/11/25 不知道干嘛的
        Page<DishDto> pageDishDto = new Page<>();
        //2 构建查询及排序条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(Dish::getName,name).orderByDesc(Dish::getUpdateTime);
        //3 执行分页条件查询
        dishService.page(pageInfo,lqw);
        // TODO: 2021/11/25 对象属性拷贝，啥原理
        //4 遍历分页查询列表数据，根据分类ID查询分类信息，从而获取该菜品的分类名称
        BeanUtils.copyProperties(pageInfo,pageDishDto,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category.getName() != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        pageDishDto.setRecords(list);

        //5 封装数据并返回
        return R.success(pageDishDto);



    }
    //修改回显数据
    @GetMapping("/{id}")
    @Cacheable(value = "DISH_CACHE",key = "'DISH'+#id")
    public R get(@PathVariable Long id){
        if(id==null){
            throw new CustomException("参数为空，请求参数id为null");
        }

        DishDto dishDto = dishService.getByIdWithFlavor(id);


        return R.success(dishDto);


    }
    @PutMapping
    @CacheEvict(value = "DISH_CACHE",allEntries = true)
    public R update(@RequestBody DishDto dishDto){
        log.info("修改菜品信息:{}",dishDto);

        dishService.updateWithFlavor(dishDto);

        //删除该菜品分类列表的缓存数据
        redisTemplate.delete(RedisKeys.DISH + dishDto.getCategoryId() + "" + dishDto.getStatus());

        return R.success("修改成功");



    }
    //删除及批量删除
    @DeleteMapping
    @CacheEvict(value = "DISH_CACHE",allEntries = true)
    public R delByIds(Long[] ids){

        if(ids.length==0){
            throw new CustomException("dishIds参数错误");
        }

        dishService.delByIdsWithFlavors(ids);

        return R.success("删除成功");

    }
    //修改及批量修改状态
    @PostMapping("/status/{status}")
    @CacheEvict(value = "DISH_CACHE",allEntries = true)
    public R status(@PathVariable Integer status,Long[] ids){
        log.info("修改及批量修改状态:{}",status,ids.toString());
        if(status==null||ids.length==0){
            throw new CustomException("状态码或ids参数有误");
        }
        System.out.println("看看这里执行了吗");
//        System.out.println(status);
//        for (Long id : ids) {
//            System.out.println(id);
//        }
        dishService.status(status,ids);

        return R.success("修改状态成功");

    }
    //根据分类id查询菜品列表
    @GetMapping("/list")
    @Cacheable(value = "DISH_CACHE",key = "'DISH'+#dish.status+''+#dish.categoryId")
    public R list(Dish dish){
        log.info("根据分类id查询菜品列表:{}",dish);
        System.out.println("看看分类id："+dish.getCategoryId());

        //构造查询条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,dish.getCategoryId())
                .eq(Dish::getStatus,1)
                .orderByAsc(Dish::getSort);
        //获取查询数据
        List<Dish> list = dishService.list(lqw);
        //处理查询数据
        List<DishDto> dishDtoList = list.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            LambdaQueryWrapper<DishFlavor> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> flavors = dishFlavorService.list(lqw2);
            if(flavors.size()!=0){
                dishDto.setFlavors(flavors);
            }


            return dishDto;

        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(RedisKeys.DISH + dish.getCategoryId() + "" + dish.getStatus(),dishDtoList);
        System.out.println("走mysql");
        return R.success(dishDtoList);
    }



}
